<template>
  <SidebarLayout title="收藏" logo-to="/apps">
    <template #sidebar>
      <div class="collect-sidebar">
        <!-- 侧边栏头部 -->
        <div class="sidebar-header">
          <div class="header-row">
            <h3 class="sidebar-title">分类</h3>
            <el-button
              type="primary"
              :icon="Plus"
              size="small"
              @click="handleCreateCategoryClick"
              circle
              title="新建分类"
            />
          </div>
        </div>

        <!-- 分类列表 -->
        <div class="category-list">
          <!-- 全部和未分类在一行显示 -->
          <div class="default-categories-row">
            <!-- 全部分类 -->
            <div
              class="category-item compact"
              :class="{ active: selectedCategoryId === null }"
              @click="handleCategorySelect(null)"
            >
              <div class="category-info">
                <el-icon class="category-icon">
                  <Grid />
                </el-icon>
                <span class="category-name">全部</span>
              </div>
              <span class="category-count">{{ total }}</span>
            </div>

            <!-- 未分类 -->
            <div
              class="category-item compact"
              :class="{ active: selectedCategoryId === '-1' }"
              @click="handleCategorySelect(-1)"
            >
              <div class="category-info">
                <el-icon class="category-icon">
                  <Document />
                </el-icon>
                <span class="category-name">未分类</span>
              </div>
              <span class="category-count">{{ uncategorizedCount }}</span>
            </div>
          </div>

          <!-- 分类树 -->
          <el-tree
            class="category-tree"
            node-key="id"
            :data="categories"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            :highlight-current="true"
            :expand-on-click-node="false"
            draggable
            default-expand-all
            @node-drop="handleNodeDrop">
            <template #default="{ node, data }">
              <div class="tree-node-content">
                <span class="tree-node-label" @click="handleCategorySelect(data)">{{ node.label }}</span>

                <div class="tree-node-actions">
                  <el-button type="text" :icon="Edit" size="small" @click="handleEditCategory(data)" />
                  <el-button type="text" :icon="Delete" size="small" class="delete-btn" @click="handleDeleteCategory(data)" />
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </div>
    </template>

    <template #content>
      <router-view/>
    </template>
  </SidebarLayout>

  <!-- 新建/编辑分类对话框 -->
  <CreateCategoryDialog
    v-model="showCreateCategoryDialog"
    :edit-data="editingCategory"
    :default-parent-id="defaultParentId"
    category-type="COLLECT"
    @create="handleCreateCategory"
    @update="handleUpdateCategory"
  />
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Grid, Edit, Delete, Document } from '@element-plus/icons-vue'
import SidebarLayout from '@/components/SidebarMenu.vue'
import { categoryApi } from '../api'
import type { CategoryListItem, CategoryRequest, DragRequest } from '../api'
import CreateCategoryDialog from '@/components/CreateCategoryDialog.vue'
import type Node from 'element-plus/es/components/tree/src/model/node'

// 路由相关
const route = useRoute()
const router = useRouter()

// 数据状态
const categories = ref<CategoryListItem[]>([])
const total = ref(0)
const uncategorizedCount = ref(0)

// 选中的分类
const selectedCategoryId = ref<string | '-1' | null>(null)

// 对话框控制
const showCreateCategoryDialog = ref(false)
const editingCategory = ref<CategoryListItem | null>(null)
const defaultParentId = ref<string | undefined>(undefined)

// 处理新建分类点击
const handleCreateCategoryClick = () => {
  editingCategory.value = null
  // 如果当前选中了分类（不是全部和未分类），则将其设置为默认父分类
  if (selectedCategoryId.value && selectedCategoryId.value !== '-1') {
    defaultParentId.value = selectedCategoryId.value
  } else {
    defaultParentId.value = undefined
  }
  showCreateCategoryDialog.value = true
}

// 处理创建分类
const handleCreateCategory = async (request: CategoryRequest) => {
  try {
    await categoryApi.create(request)
    showCreateCategoryDialog.value = false
    editingCategory.value = null
    ElMessage.success('分类创建成功')
    await loadCategories()
  } catch (error) {
    ElMessage.error('创建失败：' + (error as Error).message)
  }
}

// 处理更新分类
const handleUpdateCategory = async (id: string, request: CategoryRequest) => {
  try {
    await categoryApi.update(id, request)
    showCreateCategoryDialog.value = false
    editingCategory.value = null
    ElMessage.success('分类更新成功')
    await loadCategories()
  } catch (error) {
    ElMessage.error('更新失败：' + (error as Error).message)
  }
}

// 加载分类
const loadCategories = async () => {
  try {
    // 使用统一的分类API的tree方法，传递 type=COLLECT
    categories.value = await categoryApi.tree({ type: 'COLLECT' })

    // 获取所有收藏项以计算总数和未分类数量
    const { favoriteItemApi } = await import('../api')
    const allItems = await favoriteItemApi.getList({})

    // 总数
    total.value = allItems.length

    // 未分类数量：没有categoryId或categoryId为空的项
    uncategorizedCount.value = allItems.filter(item => !item.categoryId).length
  } catch (error) {
    console.error('加载分类失败', error)
  }
}

// 处理编辑分类
const handleEditCategory = (category: CategoryListItem) => {
  editingCategory.value = category
  showCreateCategoryDialog.value = true
}

// 处理删除分类
const handleDeleteCategory = async (category: CategoryListItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除分类"${category.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await categoryApi.delete(category.id)
    ElMessage.success('分类删除成功')
    await loadCategories()
  } catch (error) {
    // 用户取消删除时不显示错误
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error as Error).message)
    }
  }
}

// 处理节点拖拽
const handleNodeDrop = async (
  draggingNode: Node,
  dropNode: Node,
  dropType: 'before' | 'after' | 'inner',
  _event: DragEvent
) => {
  try {
    // 获取被拖拽节点的ID
    const dragNodeId = draggingNode.data.id as string

    // 构建拖拽请求
    const dragRequest: DragRequest = {
      targetId: dropNode.data.id,
      dropType: dropType
    }

    // 调用后端接口
    await categoryApi.drag(dragNodeId, dragRequest)
    ElMessage.success('分类顺序已更新')
  } catch (error) {
    ElMessage.error('拖拽失败：' + (error as Error).message)
    // 拖拽失败时重新加载分类列表以恢复原状态
    await loadCategories()
  }
}

// 处理分类选择
const handleCategorySelect = (category: CategoryListItem | null | -1) => {
  if (category === null) {
    // 全部
    selectedCategoryId.value = null
  } else if (category === -1) {
    // 未分类
    selectedCategoryId.value = '-1'
  } else {
    // 指定分类
    selectedCategoryId.value = category.id
  }

  // 构建查询参数
  const query: Record<string, string> = {}

  // 复制现有查询参数
  Object.entries(route.query).forEach(([key, value]) => {
    if (value && typeof value === 'string') {
      query[key] = value
    }
  })

  if (category === null) {
    // 全部：删除 categoryId
    delete query.categoryId
  } else if (category === -1) {
    // 未分类：设置为 '-1'
    query.categoryId = '-1'
  } else {
    // 指定分类
    query.categoryId = category.id
  }

  // 检查当前是否在详情页面或编辑页面
  const currentRouteName = route.name as string
  if (currentRouteName && (currentRouteName.includes('Detail') || currentRouteName.includes('Edit') || currentRouteName.includes('Create'))) {
    // 如果在详情/编辑/创建页面，跳转到列表页面
    router.push({ name: 'Main', query })
  } else {
    // 如果已经在列表页面，更新路由参数
    router.replace({ query })
  }
}

// 初始化
onMounted(async () => {
  await loadCategories()

  // 恢复路由状态
  const query = route.query
  if (query.categoryId) {
    const categoryIdStr = query.categoryId as string
    if (categoryIdStr === '-1') {
      selectedCategoryId.value = '-1'
    } else {
      selectedCategoryId.value = categoryIdStr
    }
  }
})

// 监听路由变化，更新选中的分类
watch(() => route.query.categoryId, (newCategoryId) => {
  if (newCategoryId === undefined) {
    selectedCategoryId.value = null
  } else if (newCategoryId === '-1') {
    selectedCategoryId.value = '-1'
  } else {
    selectedCategoryId.value = newCategoryId as string
  }
})
</script>

<style scoped>
/* 侧边栏样式 */
.collect-sidebar {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: transparent;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
  flex-shrink: 0;
}

.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.category-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.default-categories-row {
  display: flex;
  gap: 4px;
  margin-bottom: 8px;
}

.category-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  margin-bottom: 4px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.category-item.compact {
  flex: 1;
  padding: 8px 12px;
  margin-bottom: 0;
  font-size: 13px;
}

.category-item:hover {
  background: var(--el-fill-color-light);
}

.category-item.active {
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

.category-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.category-icon {
  font-size: 18px;
  flex-shrink: 0;
}

.category-item.compact .category-icon {
  font-size: 14px;
}

.category-name {
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.category-count {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color);
  padding: 2px 8px;
  border-radius: 12px;
  flex-shrink: 0;
}

.category-item.compact .category-count {
  font-size: 11px;
  padding: 1px 4px;
  min-width: 16px;
}

.category-item.active .category-count {
  background: var(--el-color-primary-light-8);
  color: var(--el-color-primary);
}

/* 深色模式适配 */
.dark .collect-sidebar {
  background: #252525;
}

.dark .sidebar-header {
  border-bottom-color: #3a3a3a;
}

.dark .sidebar-title {
  color: #e6e6e6;
}

.dark .category-item {
  color: #e6e6e6;
}

.dark .category-item:hover {
  background: rgba(66, 184, 131, 0.1);
}

.dark .category-item.active {
  background: rgba(66, 184, 131, 0.2);
  color: #42b883;
}

.dark .category-name {
  color: #e6e6e6;
}

.dark .category-count {
  background: #2d2d2d;
  color: #999999;
}

.dark .category-item.active .category-count {
  background: rgba(66, 184, 131, 0.3);
  color: #42b883;
}

/* 深色模式下的 category-list */
.dark .category-list {
  background: transparent !important;
}

/* 深色模式下的 el-tree 样式 */
.dark .category-tree {
  background: transparent !important;
  color: #e6e6e6 !important;
}

.dark :deep(.category-tree) {
  background-color: transparent !important;
  --el-bg-color: transparent !important;
}

.dark :deep(.category-tree .el-tree-node) {
  background-color: transparent !important;
  color: #e6e6e6 !important;
}

.dark :deep(.category-tree .el-tree-node__content) {
  color: #e6e6e6 !important;
  background-color: transparent !important;
}

.dark :deep(.category-tree .el-tree-node__content:hover) {
  background-color: rgba(66, 184, 131, 0.1) !important;
}

.dark :deep(.category-tree .el-tree-node.is-current > .el-tree-node__content) {
  background-color: rgba(66, 184, 131, 0.2) !important;
  color: #42b883 !important;
}

.dark :deep(.category-tree .el-tree-node__expand-icon) {
  color: #999999 !important;
}

.dark :deep(.category-tree .el-tree-node__expand-icon:hover) {
  color: #42b883 !important;
}

.dark .tree-node-content {
  color: #e6e6e6 !important;
}

.dark .tree-node-label {
  color: #e6e6e6 !important;
}

.dark :deep(.category-tree .el-tree-node__label) {
  color: #e6e6e6 !important;
}

.dark .tree-node-actions {
  color: #e6e6e6 !important;
}

.dark .delete-btn {
  color: #f56c6c !important;
}

.dark .delete-btn:hover {
  color: #f78989 !important;
}

.dark :deep(.el-button--text) {
  color: #b3b3b3 !important;
}

.dark :deep(.el-button--text:hover) {
  color: #e6e6e6 !important;
}

/* 强制覆盖 Element Plus 可能的默认样式 */
.dark :deep(.el-tree) {
  background-color: transparent !important;
}

.dark :deep(.el-tree__empty-block) {
  background-color: transparent !important;
  color: #999999 !important;
}

/* 树节点内容样式 */
.tree-node-content {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.tree-node-label {
  flex: 1;
  cursor: pointer;
}

.tree-node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.2s ease;
}

.tree-node-content:hover .tree-node-actions {
  opacity: 1;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  color: #f56c6c !important;
}

:deep(.el-button) {
  margin-left: 0;
  padding: 5px;
}
</style>
